<?php
require_once "config.php";
require_once dirname(__FILE__). '/util/connection.class.php';
require_once dirname(__FILE__). '/util/util.php';
set_time_limit(360*60);
ini_set('memory_limit', '512M');

$dbconn = Connection::getInstance();


$sql = " SELECT MIN(time_new) start_time, MAX(time_new) end_time FROM site_data ";
try
{
	$result = $dbconn->query($sql);
	if(count($result) > 0){
		$startTime = strtotime($result[0]['start_time']);
		$endTime = strtotime($result[0]['end_time']);
		do{
			$monthDuration = getMonthRange($startTime);
			$newTb = 'site_data_' . date('Y_m', $startTime);
			$sql = " DROP TABLE IF EXISTS $newTb ";														var_dump($sql);
			$result = $dbconn->execute($sql);
			$sql = " CREATE TABLE IF NOT EXISTS $newTb LIKE site_data ";								var_dump($sql);
			$result = $dbconn->execute($sql);
			if(!$result){
				return false;
			}
			
			$sql = " INSERT INTO $newTb SELECT * FROM site_data WHERE time_new>=? AND time_new<=? ";	var_dump($sql);
			$result = $dbconn->execute($sql, array($monthDuration['start'], $monthDuration['end']));
			
			$startTime = strtotime("+1 month", $startTime);
		}while (strtotime(date('Y-m', $startTime)) <= strtotime(date('Y-m', $endTime)));
	}
	return false;
}
catch (Exception $e)
{
	QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
	throw new Model_Exception($e->getMessage(), $e->getCode());
}


function getMonthRange($timestamp){
	$ret=array();
	$mdays=date('t', $timestamp);
	$ret['start']=date('Y-m-1 00:00:00', $timestamp);
	$ret['end']=date('Y-m-'.$mdays.' 23:59:59', $timestamp);
	return $ret;
}



